package abg.core.common.util.password;

import abg.core.common.util.SpringKit;
import abg.core.common.util.MathKit;
import org.springframework.context.ApplicationContext;

public class PWD {

    /**
     * 用明文生成密码
     *
     * @param plainPassword “123456”
     * @return “$2a$10$7irNpjt7oStHg8bQmqmpxempq8jkvjejU91N16xbdnSUA2oqi0lji"
     */
    public static String createPwdByPlain(String plainPassword) {
        return getBean().encode(MathKit.getMD5(plainPassword));
    }

    /**
     * 用明文密码，比对数据库密码
     *
     * @param inputPlainPassword “123456”
     * @param dbPassword         “$2a$10$7irNpjt7oStHg8bQmqmpxempq8jkvjejU91N16xbdnSUA2oqi0lji"
     */
    public static boolean checkPlainPwd(String inputPlainPassword, String dbPassword) {
        return SpringKit.getBean(BCryptPasswordEncoder.class).matches(MathKit.getMD5(inputPlainPassword), dbPassword);
    }

    /**
     * 用MD5生成密码
     *
     * @param md5Password “ead33108f6ebe724ce09c779d53ca840”
     * @return “$2a$10$7t7oStHg8bQmqmpxemirNpjpq8jkvjejU91N16xbdnSUA2oqi0lji"
     */
    public static String createPwdByMd5(String md5Password) {
        return SpringKit.getBean(BCryptPasswordEncoder.class).encode(md5Password);
    }

    /**
     * 用MD5密码，比对数据库密码
     *
     * @param inputMd5Password “ead33108f6ebe724ce09c779d53ca840”
     * @param dbPassword       “$2a$10$7irNpjt7oStHg8bQmqmpxempq8jkvjejU91N16xbdnSUA2oqi0lji"
     */
    public static boolean checkMd5Pwd(String inputMd5Password, String dbPassword) {
        return SpringKit.getBean(BCryptPasswordEncoder.class).matches(inputMd5Password, dbPassword);
    }

    private static BCryptPasswordEncoder getBean() {
        ApplicationContext context = SpringKit.getContext();
        if (context == null) {
            return new BCryptPasswordEncoder();
        } else {
            return SpringKit.getBean(BCryptPasswordEncoder.class);
        }
    }

    public static void main(String[] args) {
        //        String md5 = MathKit.getMD5("123456");
        //        System.out.println(md5);

        String pwd = createPwdByPlain("123456");
        System.out.println(pwd);
        //        System.out.println();
        //        String s1 = createPlainPwd("123");
        //        String s2 = createPlainPwd("123");
        //        String s3 = createPlainPwd("123");
        //
        //        System.out.println(s);
        //        System.out.println(s1);
        //        System.out.println(s2);
        //        System.out.println(s3);
        //        //e512babd98feb20c43fa53d11abfe3c3
        //        boolean b2 = matchPwd(MathKit.getMD5("123"), s);
        //        boolean b3 = matchPwd(MathKit.getMD5("123"), s);
        //        boolean b4 = matchPwd(MathKit.getMD5(""), s);
        //        System.out.println(b2);
        //        System.out.println(b3);
        //        System.out.println(b4);
        //
    }

}
